<?php

namespace App\Livewire;

use Faker\Provider\Text;
use Livewire\Component;
use Filament\Forms\Contracts\HasForms;
use Filament\Tables\Contracts\HasTable;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Tables\Concerns\InteractsWithTable;
use App\Models\Referral;
use Filament\Tables\Table;
use Filament\Facades\Filament;
use Filament\Tables\Columns\TextColumn;
use App\Models\User;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\Image\ImagickImageBackEnd;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use BaconQrCode\Renderer\Image\SvgImageBackEnd;

class ReferralList extends Component implements HasTable, HasForms
{
    use InteractsWithForms;
    use InteractsWithTable;

    public function table(Table $table): Table
    {
        return $table->query(Referral::query()->where('referred_by', Filament::auth()->getUser()->id))
              ->columns([
                  TextColumn::make('user_id')->label('推荐用户ID'),
                  TextColumn::make('active')->label('是否激活邮箱')->getStateUsing(function($record){
                      if(User::find($record->user_id)->email_verified_at){
                          return "已激活";
                        }else {
                          return "还未激活";
                        }
                  }),
                  TextColumn::make('created_at')->label('注册时间'),
                  TextColumn::make('referral_earning')->label('佣金'),
              ])->filters([

            ])->actions([

            ])->bulkActions([

            ])->modelLabel('推荐人记录');
    }
    public function render()
    {
        $renderer = new ImageRenderer(
            new RendererStyle(150, 1),
            new SvgImageBackEnd()
        );
        $writer = new Writer($renderer);
        $referralLink = route('filament.user.auth.register'). "?refer=".Filament::auth()->getUser()->referral_code;
        $qrcode = $writer->writeString($referralLink);
        $qrcode = str_replace('<?xml version="1.0" encoding="UTF-8"?>', "", $qrcode);
        return view('livewire.referral-list', compact(["referralLink", "qrcode"]));
    }
}
